/**
 *   类说明
 * 	@company         
 *   @creator             chenhe
 *   @create-time     2012-10-29   下午11:05:09   
 *   
 */
package com.zscg.sequence.ui;

import java.util.ArrayList;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.image.SmartImageView;
import com.zgcs.sequence.net.in.ExitRoomSelfPackage;
import com.zgcs.sequence.net.in.InPackage;
import com.zgcs.sequence.net.in.JoinRoomPackage;
import com.zgcs.sequence.net.in.RoomUsersPackage;
import com.zgcs.sequence.net.in.StartGamePackage;
import com.zgcs.sequence.tool.ServiceTool;
import com.zscg.sequence.R;
import com.zscg.sequence.data.Room;
import com.zscg.sequence.data.User;
import com.zscg.sequence.model.UserManager;
import com.zscg.sequence.service.SequenceService;
import com.zscg.sequence.ui.view.BaseListAdapter;

public class GameReadyActivity extends SequenceTitleActivity implements
		OnClickListener {

	public static final int DIALOG_INROOM = 1;
	public static final int DIALOG_GETUSERS = 2;
	public static final int DIALOG_STARTGAME = 3;

	public String[] titleSettingText = { "" };

	Room room;

	TextView firstText, endText;
	GridView userGridView;
	ArrayList<User> userList;
	UserListAdapter userListAdapter;
	Button startButton;
	ListView titleSeting;
	SimpleAdapter titleSettigAdapter;
	boolean inRoom;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.game_ready);
		inintTitle();
		firstText = (TextView) findViewById(R.id.first_circle);
		endText = (TextView) findViewById(R.id.end_circle);
		userGridView = (GridView) findViewById(R.id.userListView);
		userListAdapter = new UserListAdapter(this);
		userGridView.setAdapter(userListAdapter);

		titleSeting = (ListView) findViewById(R.id.title_setting_list);
		startButton = (Button) findViewById(R.id.start);

		Intent intent = getIntent();
		room = (Room) intent.getSerializableExtra("room");

		firstText.setText(room.keywords);
		endText.setText(room.keywords);

		SequenceService.clinet.getRoomUsers(room.roomId, -1);
		showDialog(DIALOG_GETUSERS);
	}

	@Override
	protected void addselfFilter() {
		intentFilter.addAction(ServiceTool.ORDER_RGA);
		intentFilter.addAction(ServiceTool.ORDER_RU);
		intentFilter.addAction(ServiceTool.ORDER_RISO);
		intentFilter.addAction(ServiceTool.ORDER_RISG);
	}

	@Override
	protected void disposeSelf(Context context, Intent intent) {
		String action = intent.getAction();
		if (ServiceTool.ORDER_RGA.equals(action)) {
			JoinRoomPackage joinRoom = (JoinRoomPackage) intent
					.getSerializableExtra(ServiceTool.ORDER_RGA);
			if (joinRoom != null
					&& joinRoom.getResult() == ServiceTool.RESULR_SUCESS) {
				User user = new User();
				user.setUserId(joinRoom.getUserID());
				user.setUserNickName(joinRoom.getUserNickname());

				if (user.getUserId() == UserManager.getInstance().getUser()
						.getUserId()) {
					user.setRoomOrder(true);
					dismissDialog(DIALOG_INROOM);
					SequenceService.clinet.getRoomUsers(room.roomId, 0);
				} else {
					Toast.makeText(this, user.getUserNickName() + "加入房间",
							Toast.LENGTH_LONG);
				}
				userList.add(user);
				userListAdapter.notifyDataSetChanged();
				if (userList.size() >= 2)
					startButton.setClickable(true);
			}

		} else if (ServiceTool.ORDER_RU.equals(action)) {
			RoomUsersPackage roomUser = (RoomUsersPackage) intent
					.getSerializableExtra(ServiceTool.ORDER_RU);
			if (room.roomId == roomUser.getRoomID()) {
				if (roomUser.getUserList() != null) {
					userList.addAll(roomUser.getUserList());
					userList.get(0).setRoomOrder(true);
					showStart();
					userListAdapter.notifyDataSetChanged();
				}
				dismissDialog(DIALOG_GETUSERS);

				if (userList.size() >= 2)
					startButton.setClickable(true);
			}
		} else if (ServiceTool.ORDER_RISO.equals(action)) {
			ExitRoomSelfPackage extRoom = (ExitRoomSelfPackage) intent
					.getSerializableExtra(ServiceTool.ORDER_RISO);
			if (room.roomId == extRoom.getRoomID()) {

				for (User user : userList) {
					if (user.getUserId() == extRoom.getExitUserID()) {
						userList.remove(user);
						userListAdapter.notifyDataSetChanged();
						Toast.makeText(this, user.getUserNickName() + "退出房间",
								Toast.LENGTH_LONG);
						break;
					}
				}
			}
		} else if (ServiceTool.ORDER_RISG.equals(action)) {
			StartGamePackage startGame = (StartGamePackage) intent
					.getSerializableExtra(ServiceTool.ORDER_RISG);

			int result = startGame.getResult();
			if (result == InPackage.RESULT_SUCESS) {
				if (userList.get(0).getUserId() == UserManager.getInstance()
						.getUser().getUserId())
					dismissDialog(DIALOG_STARTGAME);
				Intent mintent = new Intent(this, GamingActivity.class);
				mintent.putExtra("roomID", room.roomId);
				mintent.putExtra("ownerID", startGame.getOwnerID());
				mintent.putExtra("ownerName", startGame.getOwnerName());
				mintent.putExtra("room", room);
				startActivity(mintent);
				inRoom = true;
				finish();
				if (UserManager.getInstance().getUser().getUserId() == startGame
						.getOwnerID()) {
					// 自己是房主

				} else {
					// 自己不是房主,进入开始游戏界面

				}
			} else {

			}

		}
	}

	@Override
	protected void disposeLogin(Intent intent) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void settingListener() {
		// 邀请成员

	}

	@Override
	public void finish() {
		if (!inRoom)
			SequenceService.clinet.exitRoomSelf(room.roomId, UserManager
					.getInstance().getUser().getUserId());
		super.finish();
	}

	class UserListAdapter extends BaseListAdapter {

		public UserListAdapter(Context context) {
			super(context);
			userList = new ArrayList<User>();
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return userList.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View inflateItemView(int position, ViewGroup parent) {

			return mInflater.inflate(R.layout.game_ready_item_text_h, null);
		}

		@Override
		public Object getItemViewHolder(View convertView) {
			// TODO Auto-generated method stub
			ViewHolder viewHolder = new ViewHolder();
			viewHolder.icon = (SmartImageView) convertView
					.findViewById(R.id.user_icon);
			viewHolder.owerRoom = (ImageView) convertView
					.findViewById(R.id.room_order);
			viewHolder.userName = (TextView) convertView
					.findViewById(R.id.user_name);

			return viewHolder;
		}

		@Override
		public void fillViewHolder(int position, Object viewHolder,
				ViewGroup parent) {
			ViewHolder vHolder = (ViewHolder) viewHolder;
			User user = userList.get(position);
			vHolder.icon.setImageUrl(user.getUserPhoto());
			vHolder.owerRoom.setVisibility(View.GONE);
			if (user.isRoomOrder())
				vHolder.owerRoom.setVisibility(View.VISIBLE);

			vHolder.userName.setText(user.getUserNickName());

		}

		@Override
		protected void loadMore() {
			// TODO Auto-generated method stub

		}

		class ViewHolder {
			SmartImageView icon;
			ImageView owerRoom;
			TextView userName;

		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		ProgressDialog dialog;
		String msg = null;
		switch (id) {
		case DIALOG_INROOM:
			msg = "正在进入房间";
			break;
		case DIALOG_GETUSERS:
			msg = "正在获取房间成员";
			break;
		case DIALOG_STARTGAME:
			msg = "正在开始游戏";
			break;
		}
		dialog = new ProgressDialog(this);
		dialog.setIndeterminate(false);
		dialog.setMessage(msg);
		dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		dialog.setCancelable(true);
		dialog.show();
		return dialog;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.start:
			showDialog(DIALOG_STARTGAME);
			SequenceService.clinet.startGame(room.roomId, UserManager
					.getInstance().getUser().getUserId());

			// Intent intent = new Intent(this, GameActivity.class);
			// intent.putExtra("room", room);
			// startActivity(intent);
			break;

		}

	}

	private void showStart() {
		if (UserManager.getInstance().getUser().getUserId() == userList.get(0)
				.getUserId()) {
			startButton.setVisibility(View.VISIBLE);
			startButton.setOnClickListener(this);
			startButton.setClickable(false);
		}
	}

}
